package com.smartlazy.sequence.redis.core.redis;

import com.smartlazy.sequence.core.range.SeqRange;
import com.smartlazy.sequence.core.range.SeqRangeMgr;
import lombok.Data;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

/**
 * Redis区间管理器
 * @author xuan on 2018/5/8.
 * https://gitee.com/xuan698400/xsequence
 */
@Data
public class RedisSeqRangeMgr implements SeqRangeMgr {

    private RedisTemplate<String, Long> redisTemplate;

    /**
     * 前缀防止key重复
     */
    private final static String KEY_PREFIX = "x_sequence_";

    /**
     * 区间步长
     */
    private int step = 1000;

    /**
     * 获取指定区间名的下一个区间
     *
     * @param name 区间名
     * @return 返回区间
     */
    @Override
    public SeqRange nextRange(String name) {
        ValueOperations<String, Long> vo = this.redisTemplate.opsForValue();
        Long max = vo.increment(getRealKey(name), step);
        Long min = max - step + 1;
        return new SeqRange(min, max, name);
    }

    private String getRealKey(String name) {
        return KEY_PREFIX + name;
    }
 }
